package com.yzc.controller;

import com.yzc.client.SystemClient;
import com.yzc.Dto.LoginRequestDTO;
import com.yzc.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/user")
public class oauthController {
    @Autowired
    private SystemClient systemClient;
    @Autowired
    private JwtUtil jwtUtil; // 注入JwtUtil
    @Autowired
    private StringRedisTemplate stringRedisTemplate;//redis
    private static final Marker LOG_MARKER = MarkerFactory.getMarker("LOG");

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody LoginRequestDTO requestDTO) {
        Map<String, Object> response = systemClient.login(requestDTO);
        if (response.containsKey("name")) {
            String username = (String) response.get("name");
            String token = jwtUtil.generateToken(username); // 生成令牌
            ValueOperations<String, String> valueOps = stringRedisTemplate.opsForValue();
            valueOps.set("TOKEN:" + response.get("userid"), token, 1, TimeUnit.HOURS);
            response.put("token", token); // 将令牌添加到响应中
            log.info(LOG_MARKER, "登录成功");
        } else {
            log.info(LOG_MARKER, "登录失败");
        }

        return response;
    }
}
